package com.dys.controller;

import com.dys.entity.User;
import com.dys.service.UserService;
import com.dys.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author: 疾风
 * @ClassName: UserServlet
 * @Description: 登录控制器
 * @CreateDate: 2024/09/26
 * @Version: v1.0.0
 */
@WebServlet(urlPatterns = "/offlineSchool/UserServlet.do")
public class UserServlet extends HttpServlet {
    private final UserService userService = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if ("login".equals(method)) {
            login(req, resp);
        } else if ("logout".equals(method)) {
            logout(req, resp);
        }
    }

    /**
     * 实现登录功能
     *
     * @param req  请求域对象
     * @param resp 响应对象
     * @throws ServletException Servlet异常对象
     * @throws IOException      IO异常对象
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("-----login-----");
        // 1.接收前台页面传递过来的数据
        String uname = req.getParameter("uname");
        String pwd = req.getParameter("pwd");
        String code = req.getParameter("code");
        System.out.println("前端传递的username: " + uname);
        System.out.println("前端传递的password: " + pwd);
        System.out.println("前端传递的验证码code: " + code);
        // 验证码对了请求数据库，验证码都错了就没有必要请求数据库了：
        if (req.getSession().getAttribute("randStr").equals(code)) {
            // 2.数据处理,返回结果
            User user = userService.findOneUser(uname, pwd);
            System.out.println("数据库查询到的User信息：" + user);
            // 3.根据返回结果,给前端用户做出响应
            if (user != null) {
                // 将用户信息存入Session域中
                req.getSession().setAttribute("user", user);
                resp.getWriter().println(1);
            } else {
                resp.getWriter().println(2);
            }
        } else {
            // 验证码错误
            resp.getWriter().println(3);
            return;
        }

    }

    /**
     * 实现登出功能
     *
     * @param req  请求域对象
     * @param resp 响应对象
     * @throws ServletException Servlet对象
     * @throws IOException      IO流对象
     */
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("----logout-----");
        // 退出,注销Session
        HttpSession session = req.getSession();
        session.invalidate();
        // 跳转到login.jsp页面(重定向)
        // resp.sendRedirect("login.jsp");
        resp.sendRedirect(req.getContextPath() + "/login.jsp");
    }
}
